import 'dart:async';
import 'dart:collection';

import 'package:like_chat/blocs/bloc_provider.dart';
import 'package:like_chat/entity/Messages.dart';
import 'package:rxdart/rxdart.dart';
import 'package:web_socket_channel/io.dart';

class MessageListBloc implements BlocBase {

  final _messageList = <Messages>[];

  final IOWebSocketChannel _webSocketChannel;

  MessageListBloc(this._webSocketChannel);

  StreamController<List<Messages>> _syncController = BehaviorSubject<List<Messages>>();

  Stream<List<Messages>> get outMessagesStream => _syncController.stream;

  addMessage(Messages messages) {
    _webSocketChannel.sink.add(messages.toString());
    _messageList.insert(0, messages);
    _syncController.sink.add(UnmodifiableListView(_messageList));
  }

  addLastMessage(Messages message) {
    _messageList.add(message);
    _syncController.sink.add(UnmodifiableListView(_messageList));
  }

  addLastMessages(List<Messages> messages) {
    _messageList.addAll(messages);
    _syncController.sink.add(UnmodifiableListView(_messageList));
  }

  @override
  void dispose() {
    _syncController.close();
  }

}